package com.supermap.sdc2023.guongquan.usersvc;

import com.google.common.collect.Iterables;
import io.buji.pac4j.realm.Pac4jRealm;
import io.buji.pac4j.subject.Pac4jPrincipal;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.pac4j.core.profile.UserProfile;

import java.util.Collection;
import java.util.LinkedList;
import java.util.Optional;

public class SDC2023Realm extends Pac4jRealm {

    @Override
    protected  AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        SimpleAuthenticationInfo info = (SimpleAuthenticationInfo) super.doGetAuthenticationInfo(authenticationToken);
        Pac4jPrincipal pac4jPrincipal = Iterables.getOnlyElement(info.getPrincipals().byType(Pac4jPrincipal.class));
        UserProfile profile = pac4jPrincipal.getProfile();
        String userName = Optional.ofNullable(profile.getUsername()).orElseGet(() ->  Optional.ofNullable(profile.getAttribute("preferred_username")).map(e -> e.toString()).get());
        UserInfo userInfo = new UserInfo();
        userInfo.userName = userName;
        userInfo.id = profile.getId();
        Collection<Object> collection = new LinkedList<>();
        collection.add(userInfo);
        collection.add(pac4jPrincipal);
        SimplePrincipalCollection principalCollection = new SimplePrincipalCollection(collection, getName());
        SimpleAuthenticationInfo result = new SimpleAuthenticationInfo(principalCollection, pac4jPrincipal.getProfiles().hashCode());
        return result;
    }
}
